package client;

import common.ClientScanner;
import common.DataExchange;
import common.domain.ExamQuestions;
import common.domain.Student;
import common.domain.StudentMessage;

import java.io.IOException;
import java.net.Socket;
import java.util.*;

import static common.Constance.*;

/**
 * @author LinLe
 * @create 2020-12-24 16:29
 */
public class StudentExamSysClient {
    private String server;
    private DataExchange de;
    //对于初始化名字判断
    private boolean flag = false;
    //对于结束线程的判断
    private boolean threadFlag ;
    private Student currentStudent;
    
    public StudentExamSysClient(String server) throws IOException {
        threadFlag = true;
        System.out.println("客户端正在连接中...........");
        this.server = server;
        Socket s = new Socket(server,SERVER_PORT);
        System.out.println("已连接到服务器.............");
        de = new DataExchange(s);
    }
    
    public void start() {
        System.out.println("---------------------------欢迎进入在线考试系统----------------------------");
        try {
            while(threadFlag) {
                System.out.println("输入一下数字实现功能：");
                System.out.println("1: 学员系统" + "\n" + "2: 管理员系统" +"\n" + "0: 退出");
                System.out.print("请输入: ");
                int choose = ClientScanner.getScanner().nextInt();
                switch (choose) {
                    case 1:
                        System.out.println("正在进入学员系统...");
                        Thread.sleep(2000);
                        clientStudentLogin();
                        break;
                    case 2:
                        System.out.println("正在进入管理员系统...");
                        Thread.sleep(2000);
                        clientManagerLogin();
                        break;
                    case 0:
                        System.out.println("正在退出系统...");
                        de.sendStudentMessage(new StudentMessage(null,"BYE"));
                        flag=false;break;
                    default:
                        System.out.println("输入错误，请重新选择！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            de.close();
            System.exit(-2);
        } finally {
            de.close();
            System.exit(0);
        }
    
    }
    
    private void initName(boolean flag)  {
        while(true) {
            System.out.print("请输入账户名字: ");
            String name = ClientScanner.getScanner().next();
            System.out.print("请输入密码: ");
            String password = ClientScanner.getScanner().next();
            if(name.matches(REG_NAME) && password.matches(REG_PASSWORD)){
                try {
                    if(flag) {
                        de.sendStudentMessage(new StudentMessage(new Student(name, password), MANAGE_CHECK));
                    }else{
                        de.sendStudentMessage(new StudentMessage(new Student(name, password), USER_CHECK));
                    }
                    String s = de.receiveString();
                    if("SUCCESS".equalsIgnoreCase(s)){
                        currentStudent = new Student(name,password);
                        System.out.println("登入"+s);
                        break;
                    }
                    System.out.println(s+"\n");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~学员系统~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    private void clientStudentLogin() throws IOException, ClassNotFoundException, InterruptedException {
        initName(flag);
        System.out.println("\n\n---------------------------已进入学员系统----------------------------");
        while(threadFlag) {
            System.out.println("输入一下数字实现功能：");
            System.out.println("1: 学员模块" + "\n" + "2: 考试模块" +"\n" + "0: 退出");
            System.out.print("请输入: ");
            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    de.sendString(STU_MODEL);
                    studentModel();
                    break;
                case 2:
                    de.sendString(EXAM_MODEL);
                    ExamQuestionsModel();
                    break;
                case 0:
                    de.sendString("BYE");
                    System.out.println("正在退出管理模块...");
                    threadFlag=false;break;
                default:
                    System.out.println("输入错误，请重新选择！");
            }
        }
        
    }
    //----------------------------学员修改密码与退出操纵------------------------------------------------
    private void studentModel() throws IOException, ClassNotFoundException {
        System.out.println("\n\n---------------------------已进入学员模块----------------------------");
        while (true) {
            System.out.println("输入一下数字实现功能：");
            System.out.println("1: 密码修改" + "\n" + "0: 退出");
            System.out.print("请输入: ");
            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    de.sendString("changePassword");
                    changePsword();
                    break;
                case 0:
                    de.sendString("bye");
                    System.out.println("正在返回....");
                    return;
                default:
                    System.out.println("输入错误，请重新选择！");
            }
        }
    }
    
    private void changePsword() throws IOException, ClassNotFoundException {
        de.sendString(currentStudent.getName());
        String password = de.receiveString();
        System.out.println("现在密码是：" + password);
        while (true) {
            System.out.println("请输入修改后的密码");
            String passwordLast = ClientScanner.getScanner().next();
            if(password.matches(REG_PASSWORD)){
                de.sendString(passwordLast);
                break;
            }
        }
        
    }
    //----------------------------学员对于考试的操作------------------------------------------------
    private void ExamQuestionsModel() throws IOException, ClassNotFoundException, InterruptedException {
        
        System.out.println("\n\n---------------------------已进入考试模块----------------------------");
        while (true) {
            System.out.println("输入一下数字实现功能：");
            System.out.println("1: 开始考试" + "\n" +"2: 查询成绩\n" +"0: 退出");
            System.out.print("请输入: ");
            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    de.sendString("startTest");
                    startTest();
                    break;
                case 2:
                    findScore();
                    break;
                case 0:
                    de.sendString("bye");
                    System.out.println("正在返回....");
                    return;
                default:
                    System.out.println("输入错误，请重新选择！");
            }
        }
    }
    
    private void startTest() throws IOException, ClassNotFoundException, InterruptedException {
        Set<ExamQuestions> questions = de.receiveSet();
        int i = 1;
        ExamQuestions[] questions1 = new ExamQuestions[questions.size()];
        ExamQuestions[] eq =  questions.toArray(questions1);
        for (ExamQuestions question: eq
             ) {
            System.out.println(i+ ": " +  "question='" + question.getQuestion() + '\n' +
                    ", answer='" + question.getOptions() + '\n' +
                    ", value=" + question.getValue());
        }
        System.out.print("请输入答案(中间不要有空格)：");
        String answers = ClientScanner.getScanner().next();
        System.out.println("正在计算你的成绩");
        Thread.sleep(1500);
        for (int j = 0; j < 5; j++) {
            boolean b = eq[j].getAnswer().equalsIgnoreCase(answers.substring(j, j + 1));
            if(b){
                currentStudent.setScore(eq[i].getValue()+currentStudent.getScore());
            }
        }
        System.out.println("成绩为：" + currentStudent.getScore());
        currentStudent.setIsTested(true);
        de.sendStudent(currentStudent);
    }
    
    private void findScore() {
        if(currentStudent.getIsTested()){
            System.out.println("成绩为："+ currentStudent.getScore());
            return;
        }
        System.out.println("还没有成绩，请进行考试");
    }
    
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~管理员系统~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    private void clientManagerLogin() throws IOException, ClassNotFoundException {
        initName(!flag);
        System.out.println("\n\n---------------------------已进入管理员系统----------------------------");
        while(threadFlag) {
            System.out.println("输入一下数字实现功能：");
            System.out.println("1: 学员管理模块" + "\n" + "2: 考题管理模块" +"\n" + "0: 退出");
            System.out.print("请输入: ");
            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    de.sendString(STU_MANAGE_CHECK);
                    studentManagerModel();
                    break;
                case 2:
                    de.sendString(EXAM_TEST_CHECK);
                    ExamQuestionsManagerModel();
                    break;
                case 0:
                    de.sendString("BYE");
                    System.out.println("正在退出...");
                    threadFlag=false;break;
                default:
                    System.out.println("输入错误，请重新选择！");
            }
        }
        
    }
    
    //----------------------------学员的增删改查------------------------------------------------
    private void studentManagerModel() throws IOException, ClassNotFoundException {
    System.out.println("\n\n---------------------------已进入学员管理系统----------------------------");
    while(true) {
        System.out.println("输入一下数字实现功能：");
        System.out.println("1: 添加学员" + "\n" + "2: 删除学员" +"\n" + "3: 查找学员" +"\n"+"4: 修改学员" +"\n"+"5: 显示所有学员" +"\n"+"0: 返回");
        System.out.print("请输入: ");
        int choose = ClientScanner.getScanner().nextInt();
        switch (choose) {
            case 1:
                de.sendString("add");
                addStu();
                break;
            case 2:
                de.sendString("delete");
                delStu();
                break;
            case 3:
                de.sendString("find");
                findStu();
                break;
            case 4:
                de.sendString("change");
                changeStu();
                break;
            case 5:
                System.out.println("5----");
                de.sendString("show");
                showStu();
                System.out.println("5++++");
                break;
            case 0:
                de.sendString("bye");
                System.out.println("正在返回....");
                return;
            default:
                System.out.println("输入错误，请重新选择！");
        }
    }
}
    private void addStu() throws IOException, ClassNotFoundException {
    System.out.print("请输入学生名字：");
    String name = ClientScanner.getScanner().next();
    System.out.print("请输入学生密码：");
    String password = ClientScanner.getScanner().next();
    if(name.matches(REG_NAME) && password.matches(REG_PASSWORD)) {
        de.sendStudent(new Student(name, password));
        String s = de.receiveString();
        System.out.println(s);
    }else{
        System.out.println("不正确");
    }
}
    private void delStu() throws IOException, ClassNotFoundException {
        System.out.print("请输入要删除的学生的名字：");
        String name = ClientScanner.getScanner().next();
        de.sendString(name);
        String s = de.receiveString();
        System.out.println(s);
    }
    private void changeStu() throws IOException, ClassNotFoundException {
        System.out.print("请输入要修改的学生的名字：");
        String name = ClientScanner.getScanner().next();
        de.sendString(name);
        Student s = de.receiveStudent();
        if(  s == null) {
            System.out.println("没有此人");
        }else{
            System.out.println("学生的信息如下："+ s+"\n");
            addStu();
        }
        
        
    }
    private void findStu() throws IOException, ClassNotFoundException {
        System.out.print("请输入要找的学生的名字：");
        String name = ClientScanner.getScanner().next();
        de.sendString(name);
        StudentMessage s = de.receiveStudentMessage();
        if(  s.getStudent() == null) {
            System.out.println("没有此人");
        }else{
            System.out.println("学生的信息如下："+ s.getStudent());
        }
    }
    private void showStu() throws IOException, ClassNotFoundException {
        String s = de.receiveString();
        if("有人了".equalsIgnoreCase(s)){
//--------------------------------------------------------------
            //接受Map对象
            HashMap<String, Student> students = de.receiveCol();
            Set<Map.Entry<String, Student>> set = students.entrySet();
            System.out.println("--------一下是全体学员名单---------");
            set.stream().map(Map.Entry::getValue).forEach(System.out::println);
            //-----------------------------------------------------------------
            //接收Student对象
//            Student student = null;
//            while((student = de.receiveStudent() )!= null){
//                System.out.println(student);
//            }
//            String s1 = de.receiveString();
//            System.out.println(s1);
        } else{
            System.out.println(s);
        }
    }
    //----------------------------考题的增删改查------------------------------------------------
    private void ExamQuestionsManagerModel() throws IOException, ClassNotFoundException {
        System.out.println("\n\n---------------------------已进入学员管理系统----------------------------");
        while(true) {
            System.out.println("输入一下数字实现功能：");
            System.out.println("1: 添加题目" + "\n" + "2: 删除题目" +"\n" + "3: 查找题目" +"\n"+"4: 修改题目" +"\n"+"5: 显示所有题目" +"\n"+"0: 返回");
            System.out.print("请输入: ");
            int choose = ClientScanner.getScanner().nextInt();
            switch (choose) {
                case 1:
                    de.sendString("add");
                    addExam();
                    break;
                case 2:
                    de.sendString("delete");
                    delExam();
                    break;
                case 3:
                    de.sendString("find");
                    findExam();
                    break;
                case 4:
                    de.sendString("change");
                    changeExam();
                    break;
                case 5:
                    System.out.println("5----");
                    de.sendString("show");
                    showExam();
                    System.out.println("5++++");
                    break;
                case 0:
                    de.sendString("bye");
                    System.out.println("正在返回....");
                    return;
                default:
                    System.out.println("输入错误，请重新选择！");
            }
        }
    }
    
    private void addExam() throws IOException, ClassNotFoundException {
        ClientScanner.getScanner().nextLine();
         System.out.println("请输入题目：");
         String title = ClientScanner.getScanner().nextLine();
         System.out.println("请输入选项：");
         String option = ClientScanner.getScanner().nextLine();
         System.out.println("请输入分值：");
         int value = ClientScanner.getScanner().nextInt();
        System.out.println("请输入答案：");
        String answer = ClientScanner.getScanner().next();
         de.sendExamQuestions(new ExamQuestions(title,option,value,answer));
         String s = de.receiveString();
         System.out.println(s);
 }
    private void delExam() throws IOException, ClassNotFoundException {
        ClientScanner.getScanner().nextLine();
        System.out.print("请输入要删除的题目：");
        String title = ClientScanner.getScanner().nextLine();
        de.sendString(title);
        String s = de.receiveString();
        System.out.println(s);
    }
    private void changeExam() throws IOException, ClassNotFoundException {
        ClientScanner.getScanner().nextLine();
        System.out.print("请输入要修改的题目：");
        String title = ClientScanner.getScanner().nextLine();
        de.sendString(title);
        ExamQuestions s = de.receiveExamQuestions();
        if(  s == null) {
            System.out.println("没有此题目");
        }else{
            System.out.println("题目的信息如下："+ s+"\n");
            System.out.println("请输入题目：");
            String title1 = ClientScanner.getScanner().nextLine();
            System.out.println("请输入选项：");
            String option = ClientScanner.getScanner().nextLine();
            System.out.println("请输入分值：");
            int value = ClientScanner.getScanner().nextInt();
            System.out.println("请输入答案：");
            String answer = ClientScanner.getScanner().next();
            de.sendExamQuestions(new ExamQuestions(title,option,value,answer));
            String s1 = de.receiveString();
            System.out.println(s1);
        }
        
        
    }
    private void findExam() throws IOException, ClassNotFoundException {
        ClientScanner.getScanner().nextLine();
        System.out.print("请输入要找的题目：");
        String title = ClientScanner.getScanner().nextLine();
        de.sendString(title);
        ExamQuestions s = de.receiveExamQuestions();
        if(  s == null) {
            System.out.println("没有此人");
        }else{
            System.out.println("题目的信息如下："+ s);
        }
    }
    private void showExam() throws IOException, ClassNotFoundException {
        String s = de.receiveString();
        if("有题目了".equalsIgnoreCase(s)){
//--------------------------------------------------------------
            //接受Map对象
            Set<ExamQuestions> examQuestions = de.receiveSet();
            System.out.println("--------一下是全部的题目---------");
            examQuestions.stream().forEach(System.out::println);
            //-----------------------------------------------------------------
            //接收Student对象
//            Student student = null;
//            while((student = de.receiveStudent() )!= null){
//                System.out.println(student);
//            }
//            String s1 = de.receiveString();
//            System.out.println(s1);
        } else{
            System.out.println(s);
        }
    }
    
}
